<template>
  <div v-loading="loading" class="rc-cont">
    <flexbox v-if="!isSeas" class="rc-head" direction="row-reverse">
      <el-button class="rc-head-item" type="primary" @click="addFile">上传附件</el-button>
      <input id="file" type="file" class="rc-head-file" accept="*/*" multiple @change="uploadFile">
    </flexbox>
    <el-table :data="list" :height="tableHeight" class="file-table" stripe
              style="width: 100%;border: 1px solid #E6E6E6;" @row-click="handleRowClick">
      <el-table-column v-for="(item, index) in fieldList" :key="index"
                       :prop="item.prop" :label="item.label" show-overflow-tooltip/>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <!--        <template slot-scope="scope">-->
          <flexbox>
            <el-button link @click="handleFile('preview', scope)">预览</el-button>
            <el-button link @click="handleFile('download', scope)">下载</el-button>
            <el-button :disabled="scope.row.readOnly == 1" link
                       @click="handleFile('edit', scope)">重命名
            </el-button>
            <el-button :disabled="scope.row.readOnly == 1" link @click="handleFile('delete', scope)">
              删除
            </el-button>
          </flexbox>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :append-to-body="true" :close-on-click-modal="false"
               v-model="editDialog" title="编辑" width="30%">
      <el-form :model="editForm">
        <el-form-item label="新名称" label-width="100">
          <el-input v-model="editForm.name" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="editDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmEdit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {crmFileDeleteAPI, crmFileUpdateAPI, downloadFileAPI} from '/src/api/common.js'

import {crmLeadsFileListAPI} from '/src/api/crm/leads.js'
import {crmCustomerFileListAPI} from '/src/api/crm/customer.js'
import {crmContactsFileListAPI} from '/src/api/crm/contacts.js'
import {crmBusinessFileListAPI} from '/src/api/crm/business.js'
import {crmContractFileListAPI} from '/src/api/crm/contract.js'
import {crmProductFileListAPI} from '/src/api/crm/product.js'
import {crmReceivablesFileListAPI} from '/src/api/crm/receivables.js'
import {crmReceivablesPlanFileListAPI} from '/src/api/crm/receivablesPlan.js'
import {crmReturnVisitFileAPI} from '/src/api/crm/visit.js'
import {crmInvoiceFileListAPI} from '/src/api/crm/invoice.js'

import {fileSize, canPreviewFile, wkPreviewFile, downloadFileWithBuffer} from '/src/utils/index.js'
import {debounce} from 'throttle-debounce'

const cxt = getCurrentInstance()
const bus = cxt.appContext.config.globalProperties.$bus
const $wkUploadFile = cxt.appContext.config.globalProperties.$wkUploadFile
const $wkPreviewFile = cxt.appContext.config.globalProperties.$wkPreviewFile


defineOptions({
  name: 'RelativeFiles', // 相关附件  可能再很多地方展示 放到客户管理目录下
})

const props = defineProps({
  /** 模块ID */
  id: [String, Number],
  /** 联系人人下 新建商机 需要联系人里的客户信息  合同下需要客户和商机信息 */
  detail: {
    type: Object,
    default: () => {
      return {}
    }
  },
  /** 没有值就是全部类型 有值就是当个类型 */
  crmType: {
    type: String,
    default: ''
  },
  /** 是公海 默认是客户 */
  isSeas: {
    type: Boolean,
    default: false
  }
})


const loading = ref(false)
const list = ref([])
const fieldList = ref([])
const tableHeight = ref('400px')
/** 重命名 弹窗 */
const editDialog = ref(false)
/** 编辑信息 */
const editForm = ref({name: '', data: {}})

const rootTabs =  inject('rootTabs')
let debouncedGetDetail = () => {}

watch(() => props.id, (val) =>  {
  list.value = []
  getDetail()
})

watch(() => rootTabs.currentName, (val)=> {
  if (val === 'RelativeFiles') {
    getDetail(false)
  }
})

onMounted(() => {
  fieldList.value.push({prop: 'name', width: '200', label: '附件名称'})
  fieldList.value.push({prop: 'size', width: '100', label: '附件大小'})
  fieldList.value.push({
    prop: 'createUserName',
    width: '100',
    label: '上传人'
  })
  fieldList.value.push({
    prop: 'createTime',
    width: '200',
    label: '上传时间'
  })
  fieldList.value.push({prop: 'source', width: '100', label: '来源'})
  getDetail()

  debouncedGetDetail = debounce(300, () => {
    bus.emit('crm-tab-num-update')
    getDetail()
  })
})


function getDetail(loading = true) {
  loading.value = loading
  const request = {
    leads: crmLeadsFileListAPI,
    customer: crmCustomerFileListAPI,
    contacts: crmContactsFileListAPI,
    business: crmBusinessFileListAPI,
    contract: crmContractFileListAPI,
    product: crmProductFileListAPI,
    receivables: crmReceivablesFileListAPI,
    receivablesPlan: crmReceivablesPlanFileListAPI,
    visit: crmReturnVisitFileAPI,
    invoice: crmInvoiceFileListAPI
  }[props.crmType]
  const params = {}
  params[`id`] = props.id
  request(params).then(res => {
    loading.value = false
    list.value = res.data.data.map(item => {
      item.size = fileSize(item.size)
      return item
    })
  }).catch(() => {
    loading.value = false
  })
}
function addFile() {
  document.getElementById('file').click()
}
/** 图片选择出发 */
function uploadFile(event) {
  var files = event.target.files
  for (let index = 0; index < files.length; index++) {
    const file = files[index]
    var params = {}
    params.batchId = props.detail.batchId
    params.file = file
    $wkUploadFile.upload({
      file: file,
      params: {
        batchId: props.detail.batchId
      }
    }).then(completeData => {
      debouncedGetDetail()
    }).catch(() => {
    })
  }

  event.target.value = ''
}
// 当某一行被点击时会触发该事件
function handleRowClick(row, column, event) {
}

function showPreviewBtn(item) {
  return canPreviewFile(item.row.name)
}

/**
 * 编辑删除cell
 */
function handleFile(type, item) {
  if (type === 'preview') {
    if (canPreviewFile(item.row.name)) {
      wkPreviewFile(item.row.url, item.row.name)
    } else {
      $wkPreviewFile.preview({
        index: item.$index,
        data: list.value
      })
    }
  } else if (type === 'delete') {
    ElMessageBox.confirm('您确定要删除该文件吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
          crmFileDeleteAPI({
            id: item.row.fileId
          }).then(res => {
                list.value.splice(item.$index, 1)
                bus.emit('crm-tab-num-update')
                ElMessage.success({message: '操作成功'})
          }).catch(() => {})
        })
        .catch(() => {
        })
  } else if (type === 'download') {
    downloadFileAPI(item.row.url).then(res => {
      const blob = new Blob([res.data], {
        type: ''
      })
      downloadFileWithBuffer(blob, item.row.name)
    }).catch(() => {
    })
  } else {
    editForm.value.data = item
    editForm.value.name = item.row.name
    editDialog.value = true
  }
}
function confirmEdit() {
  if (editForm.value.name) {
    crmFileUpdateAPI({
      fileId: editForm.value.data.row.fileId,
      name: editForm.value.name
    }).then(res => {
          ElMessage.success({message: '编辑成功'})
          editDialog.value = false
          let item = list.value[editForm.value.data.$index]
          item.name = editForm.value.name
    }).catch(() => {})
  }
}

</script>
<script type="text/javascript">


export default {
  components: {},
  props: {},
  data() {
    return {}
  },
  // inject: ['rootTabs'],
  computed: {},
  watch: {

  },
  mounted() {

  },
  methods: {

  }
}
</script>
<style lang="scss" scoped>
@import '../../styles/relativecrm';

.h-item {
  font-size: 13px;
  color: #409eff;
  margin: 0 5px;
  cursor: pointer;
}

.rc-head-file {
  position: absolute;
  top: 0;
  right: 0;
  height: 98px;
  width: 98px;
  opacity: 0;
  z-index: -1;
  cursor: pointer;
}
</style>

